package com.gitee.sergius.apitool.parser.convertor.request;

import com.gitee.sergius.apitool.annotation.ApiModel;
import com.gitee.sergius.apitool.annotation.ApiModelProperty;
import com.gitee.sergius.apitool.constant.Constant;
import com.gitee.sergius.apitool.entity.RequestParamEntity;
import com.gitee.sergius.apitool.constant.DataType;
import org.springframework.util.StringUtils;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

/**
 * @author shawn yang
 * @version 1.0.0
 * <p><pre>用于解析{@link ApiModel}定义的封装类中{@link ApiModelProperty}标签定义的请求参数</pre>
 *
 */
public class RequestModelToEntityConvertor {

    /**
     * 由自定义封装类型转换成实体
     * @param clazz 封装类
     * @param level 该参数所处的数据层级
     */
    public static List<RequestParamEntity> parseModelToEntity(Class clazz , int level) {
        List<RequestParamEntity> requestParamEntityList = new ArrayList<>();

        if(level > Constant.PARSE_DEPTH){
            return requestParamEntityList;
        }

        Field[] fields = clazz.getDeclaredFields();

        for (Field field : fields) {
            if (!field.isAnnotationPresent(ApiModelProperty.class)) {
                continue;
            }

            ApiModelProperty apiModelProperty = field.getAnnotation(ApiModelProperty.class);

            Class paramClazz = field.getType();

            String name = StringUtils.isEmpty(apiModelProperty.name())?field.getName():apiModelProperty.name();
            String desc = apiModelProperty.desc();
            boolean required = apiModelProperty.required();
            String example = apiModelProperty.example();

            if (paramClazz.isAnnotationPresent(ApiModel.class)) {

                RequestParamEntity requestParamEntity = new RequestParamEntity();
                requestParamEntity.setName(name);
                requestParamEntity.setDesc(desc);
                requestParamEntity.setRequired(required);
                requestParamEntity.setArray(false);
                requestParamEntity.setLevel(level);
                requestParamEntity.setHasChild(true);
                requestParamEntity.setType(DataType.CLASS.getName());
                requestParamEntity.setChildList(parseModelToEntity(paramClazz,level+1));

                requestParamEntityList.add(requestParamEntity);
            } else {

                RequestParamEntity requestParamEntity = RequestNotModelToEntityConvertor.parseNotModelToEntity(field.getType(),field.getGenericType(),
                        name,desc,required,example,level);

                requestParamEntityList.add(requestParamEntity);
            }

        }

        return requestParamEntityList;
    }

}
